package com.xexun.gpstracker.msg;

import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.baby.MyPullUpListView;
import com.xexun.gpstracker.baby.activity.ChatActivity;
import com.xexun.gpstracker.baby.activity.DoubleDatePickerDialog;
import com.xexun.gpstracker.baby.mytree.Warning;
import com.xexun.gpstracker.baby.mytree.WarningListAdapter;
import com.xexun.gpstracker.msg.view.InputDialog;
import com.xexun.gpstracker.pojo.ChatMsg;
import com.xexun.gpstracker.pojo.Device;
import com.xexun.gpstracker.pojo.Friend;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.HttpUtil;
import com.xexun.gpstracker.util.Utils;
import com.xexun.gpstracker.vo.ContType;
import com.xexun.gpstracker.vo.RelationType;
import com.xexun.gpstracker.vo.Session;
import com.xexun.gpstracker.vo.TermType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;


/**
 * 消息界面
 */
public class MsgMainFragment extends Fragment {
    private FragmentManager fragmentManager = null;
    private Fragment msgFragment;
    private Fragment contactFragment;
    private MsgSelectFragment selectFragment;
    private Fragment currFragment;
    private Button   groupSendBtn;
    private Button   selectBtn;
    private Button rightWarningBtn;
    private TextView cancelTextView;
    private InputDialog dialog;
    private List<Friend> friends = new ArrayList<>();
    private List<Friend> groupSendfriends = new ArrayList<>();

    public static Map<String, Uri> mEmoticonsUri = new HashMap<String, Uri>();
    public static List<String> mEmoticonsNewGif = new ArrayList<>();
    private Boolean canselected = true;



    //报警列表
    private MyPullUpListView warningListView;
    private Boolean hasNext;
    private String startStr;
    private String endStr;
    private int page = 1;
    private List<Warning> list;
    private WarningListAdapter warningApater;

    @ViewInject(R.id.mainMsg)
    private TextView mainMsg;

    @ViewInject(R.id.mainContact)
    private TextView mainContact;

    public static MsgMainFragment newInstance() {
        return new MsgMainFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_msg_main, null);
        x.view().inject(this, view);


        //群发
        groupSendBtn = (Button)view.findViewById(R.id.groupSend);
        rightWarningBtn = (Button)view.findViewById(R.id.msgRightWarningBtn);
        cancelTextView = (TextView)view.findViewById(R.id.cancel);
        selectBtn = (Button)view.findViewById(R.id.selectBtn);
        warningListView = (MyPullUpListView) view.findViewById(R.id.warning);

        rightWarningBtn.setVisibility(View.GONE);

        init();

        rightWarningBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(warningListView.getVisibility() == View.VISIBLE){
                    warningListView.setVisibility(View.GONE);
                }else{
                    ShowDateDialog();
                }


            }
        });



       abstract class NoDoubleClickListener implements View.OnClickListener {
            public static final int MIN_CLICK_DELAY_TIME = 1000;
            private long lastClickTime = 0;

            @Override
            public void onClick(View v) {
                long currentTime = Calendar.getInstance().getTimeInMillis();
                if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
                    lastClickTime = currentTime;
                    onNoDoubleClick(v);
                }
            }

            protected abstract void onNoDoubleClick(View v);

        }


       selectBtn.setOnClickListener(new NoDoubleClickListener() {
           @Override
           protected void onNoDoubleClick(View v) {

               try{
                   if(selectFragment.mAdapter.selectImeiList.size() == 0 && selectFragment.mAdapter.terminalSet.size() == 0 ){
                       Toast.makeText(getActivity(),"请选择发送设备！",Toast.LENGTH_SHORT).show();
                       return;
                   }

                   if(null == dialog ){
                       dialog = new InputDialog(getActivity(),R.style.dialog,onClickListener,getString(R.string.mass_send));
                   }
                   if(!dialog.isShowing()){
                       dialog.show();
                   }
               }catch (NullPointerException e){


               }



           }
       });






        groupSendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             if(canselected){
                canselected = false;
                 selectFragment = MsgSelectFragment.newInstance();
                 selectFragment.setOnSelectClickListener(new MsgSelectFragment.OnSelectClickListener() {
                     @Override
                     public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//                         if(selectFragment.listView.getCheckedItemCount() == 0 ){
//                             selectBtn.setText("选择");
//                         }else {
//                             selectBtn.setText("已选("+String.valueOf(selectFragment.listView.getCheckedItemCount())+")");
//                         }
                     }
                 });
//                 rightWarningBtn.setVisibility(View.GONE);
                 fragmentManager.beginTransaction().replace(R.id.msg_fragment_place_holder, selectFragment).commit();
                 cancelTextView.setVisibility(View.VISIBLE);
                 selectBtn.setVisibility(View.VISIBLE);
                 groupSendBtn.getBackground().setAlpha(0);
//                 selectFragment.mAdapter.notifyDataSetChanged();
//
//                 selectFragment.listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//                 selectBtn.setText(R.string.send);

             }else{
                 setGroupBtn();
                 groupSendfriends.clear();
             }

            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            fragmentManager = getChildFragmentManager();
        } else {
            fragmentManager = getFragmentManager();
        }
        msgFragment = MsgFragment.newInstance();
        fragmentManager.beginTransaction().replace(R.id.msg_fragment_place_holder, msgFragment).commit();
        this.currFragment = msgFragment;

        //加载本地表情
        loadLocalEmoticon();
        return view;
    }

    private void setGroupBtn(){
        canselected = true;
        selectFragment = null;
        fragmentManager.beginTransaction().replace(R.id.msg_fragment_place_holder, msgFragment).commit();
//        selectBtn.setText("选择");
        selectBtn.setText("发送");
        cancelTextView.setVisibility(View.GONE);
        selectBtn.setVisibility(View.GONE);
        groupSendBtn.getBackground().setAlpha(255);
//        rightWarningBtn.setVisibility(View.VISIBLE);
    }

//    static final String Msg_WARNINGURL = "http://120.25.75.101:8080/terminal/getAlarms";
      static final String Msg_WARNINGURL = Constants.baseUrl+"terminal/getAlarms";

//   static final String Msg_TERMINALURL = "http://192.168.1.189:8080/terminal/sendMessage";
     static final String Msg_TERMINALURL = Constants.baseUrl+"terminal/sendMessage";

    private void ShowDateDialog(){
        Calendar c = Calendar.getInstance();

        // 最后一个false表示不显示日期，如果要显示日期，最后参数可以是true或者不用输入
        new DoubleDatePickerDialog(getActivity(), 0, new DoubleDatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                  int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear,
                                  int endDayOfMonth) {
                //日期回调
                String textString = String.format("开始时间：%d-%d-%d\n结束时间：%d-%d-%d\n", startYear,
                        startMonthOfYear + 1, startDayOfMonth, endYear, endMonthOfYear + 1, endDayOfMonth);
                page = 1;
                String startDateString = String.format("%d-%d-%d", startYear, startMonthOfYear + 1, startDayOfMonth);
                String endDateString   = String.format("%d-%d-%d", endYear, endMonthOfYear + 1, endDayOfMonth);
                startStr = startDateString;
                endStr = endDateString;

//                               Toast.makeText(getActivity(),textString,Toast.LENGTH_LONG).show();

                JSONObject jsonObj = new JSONObject();
                final Session instance = Session.getInstance();
                try {

//                    SharedPreferences sp = Utils.getPreferences(getActivity());
//                    int mDeviceId = sp.getInt("mDevice",0) ;
                    if (instance == null||instance.getDevice()==null){
                        jsonObj.put("termId","");
                    }else {
                        jsonObj.put("termId", instance.getDevice().getId()) ;
                    }
                    jsonObj.put("startTime",startDateString) ;
                    jsonObj.put("endTime",endDateString) ;
                    jsonObj.put("page",0) ;

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                HttpUtil.post(Msg_WARNINGURL, jsonObj, new Callback.ProgressCallback<JSONObject>() {
                    @Override
                    public void onWaiting() {

                    }

                    @Override
                    public void onStarted() {

                    }

                    @Override
                    public void onLoading(long total, long current, boolean isDownloading) {

                    }

                    @Override
                    public void onSuccess(JSONObject result) {

                        JSONObject body = null;
                        try {
                            body = result.getJSONObject("body");
                            final JSONArray warningArray = body.getJSONArray("data");
                            hasNext = body.getBoolean("hasNext");
                            list = new ArrayList<Warning>();

                            for(int i = 0 ; i< warningArray.length();i++){
                                JSONObject obj = (JSONObject) warningArray.get(i);
                                Warning warning = new Warning(obj.getString("alarmContentLocal"),obj.getString("uploadTime"),obj.getString("id"));
                                list.add(warning);
                            }

                            if(list.size() == 0){
                                return;
                            }


//                                            warningListView = new MyPullUpListView(getActivity());
//                                            warningListView.setBackgroundResource(R.color.white);
                            warningListView.setVisibility(View.VISIBLE);
//                                            listViewRL.addView(warningListView,2);
                            warningListView.initBottomView();
//                                          warningApater = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1,list);
                            warningApater = new WarningListAdapter(getActivity(),list);
                            warningListView.setAdapter(warningApater);
                            warningListView.setMyPullUpListViewCallBack(new MyPullUpListView.MyPullUpListViewCallBack() {
                                @Override
                                public void scrollBottomState() {
                                    if(hasNext){
                                        //刷新

                                        JSONObject jsonObj = new JSONObject();
                                        try {
//                                            SharedPreferences sp = Utils.getPreferences(getActivity());
//                                            int mDeviceId = sp.getInt("mDevice",0) ;
                                            jsonObj.put("termId", instance.getDevice().getId()) ;
                                            jsonObj.put("startTime",startStr) ;
                                            jsonObj.put("endTime",endStr) ;
                                            jsonObj.put("page",++page) ;

                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        HttpUtil.post(Msg_WARNINGURL, jsonObj, new Callback.ProgressCallback<JSONObject>() {
                                            @Override
                                            public void onWaiting() {

                                            }

                                            @Override
                                            public void onStarted() {

                                            }

                                            @Override
                                            public void onLoading(long total, long current, boolean isDownloading) {

                                            }

                                            @Override
                                            public void onSuccess(JSONObject result) {

                                                JSONObject body = null;
                                                try {
                                                    body = result.getJSONObject("body");
                                                    final JSONArray warningArray = body.getJSONArray("data");
                                                    hasNext = body.getBoolean("hasNext");
                                                    for(int i = 0 ; i< warningArray.length();i++){
                                                        JSONObject obj = (JSONObject) warningArray.get(i);
                                                        Warning warning = new Warning(obj.getString("alarmContentLocal"),obj.getString("uploadTime"),obj.getString("id"));
                                                        list.add(warning);
                                                    }

                                                    if(list.size() == 0){
                                                        return;
                                                    }
                                                    warningApater.notifyDataSetChanged();
//                                                             warningListView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1,list));
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }


                                            }

                                            @Override
                                            public void onError(Throwable ex, boolean isOnCallback) {

                                            }

                                            @Override
                                            public void onCancelled(Callback.CancelledException cex) {

                                            }

                                            @Override
                                            public void onFinished() {

                                            }
                                        });



                                    }else{
                                        warningListView.setFooterText(getString(R.string.loaded));
                                    }




                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });




            }


        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), true).show();



    }




    private void init() {
        friends.clear();
        List<Device> devices = Session.getInstance().getMonitors();
        if (CommUtil.isNotEmpty(devices)) {
            for (int i = 0; i < devices.size(); i++) {
                if (!devices.get(i).isBinded()) {
                    continue;
                }
                Friend friend = new Friend();
                friend.setId((long) i);
                friend.setName(devices.get(i).getName());
                friend.setImei(devices.get(i).getImei());
                friend.setPhoto(devices.get(i).getPortrait());
                friend.setPhone(devices.get(i).getPhone());
                friend.setSortLetters(getString(R.string.watch));
                friend.setTermType(TermType.WATCH);
                friend.setOnline(devices.get(i).getOnline() == 1);
                friend.setRelationType(RelationType.MONITOR_OBJECT);
                friends.add(friend);
            }
        }
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override  public void onClick(View v) {
           final String input = dialog.text_input.getText().toString();

           if(input.isEmpty()){
               Toast.makeText(getActivity(),"发送内容不能为空！",Toast.LENGTH_SHORT).show();
               return;
           }

            Thread  t = new Thread(new Runnable(){
                public void run(){
                    dialog.dismiss();
                    groupSendfriends.clear();
                    if(null != selectFragment && null != selectFragment.mAdapter.selectImeiList && selectFragment.mAdapter.selectImeiList.size() != 0){
                        for(String name : selectFragment.mAdapter.selectImeiList){
                            ChatMsg chatMsg = new ChatMsg();
                            chatMsg.setIsSend(true);
                            chatMsg.setIsRead(1);
                            chatMsg.setImei(name);
                            Log.i(getActivity().getClass().getName(),"chat_name:"+name);
                            chatMsg.setType(0);
                            chatMsg.setTermType(0);
                            chatMsg.setContent(input);
                            chatMsg.setUserId(Session.getInstance().getLoginedUserId());
                            chatMsg.setTime(System.currentTimeMillis());
                            groupSend(chatMsg);
                        }
                    }

                    if(null != selectFragment && null != selectFragment.mAdapter.terminalSet && selectFragment.mAdapter.terminalSet.size() != 0){


                        try {
                            JSONObject json = new JSONObject();

                            Set<String> set = selectFragment.mAdapter.terminalSet;
                            json.putOpt("ids",new JSONArray(set));
                            json.put("content",input);
                            HttpUtil.post(Msg_TERMINALURL,json, new Callback.ProgressCallback<JSONObject>() {
                                @Override
                                public void onSuccess(JSONObject result) {
                                    Toast.makeText(getActivity(),"机构消息发送成功！",Toast.LENGTH_SHORT).show();

                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    Toast.makeText(getActivity(),"机构消息发送失败！",Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onCancelled(CancelledException cex) {

                                }

                                @Override
                                public void onFinished() {

                                }

                                @Override
                                public void onWaiting() {

                                }

                                @Override
                                public void onStarted() {

                                }

                                @Override
                                public void onLoading(long total, long current, boolean isDownloading) {

                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }



                    }

                }});
            t.start();
            Toast.makeText(getActivity(),getString(R.string.about_feedback_succ),Toast.LENGTH_LONG).show();
            setGroupBtn();


//            Toast.makeText(getActivity(),input,Toast.LENGTH_SHORT).show();
        }
    };

    //发送群组消息
    private void groupSend(ChatMsg chatMsg){
            try {
                AppContext.db.saveBindingId(chatMsg);
            } catch (Exception e) {
                Log.e(Constants.TAG, "保存聊天信息到数据库失败！", e);
            }
            AppContext.getEventBus().post(chatMsg, Constants.EVENT_TAG_CHAT_SEND);
    }




    /**
     * 加载表情,加载本地指定文件夹下的表情，如果存在，则加载，不存在则不加载。
     */
    private void loadLocalEmoticon() {
        Log.d(Constants.TAG, "开始加载本地表情");
        File gifFile = new File(getActivity().getFilesDir() + "/emoji/gif/");
        File[] files = gifFile.listFiles();
        if (files != null) {
            mEmoticonsNewGif.clear();
            mEmoticonsUri.clear();
            for (int i = 0; i < files.length; i++) {
                //判断是否为文件夹
                if (!files[i].isDirectory()) {
                    String mFileName = files[i].getName();
                    Pattern p = Pattern.compile("zgif[0-9][0-9].gif");
                    Matcher m = p.matcher(mFileName);
                    if (m.matches()) {
                        //将String类型的路径转换为Uri
                        mFileName = "[" + mFileName + "]";
                        mEmoticonsNewGif.add(mFileName);
                        mEmoticonsUri.put(mFileName, Uri.fromFile(files[i]));
                    }

                }
            }
            Log.d(Constants.TAG, "表情的条数：mEmoticonsNewGif:" + mEmoticonsNewGif.size());
            Log.d(Constants.TAG, "表情的条数：mEmoticonsUri:" + mEmoticonsUri.size());
        }

    }

    @Event(R.id.mainMsg)
    private void msgOnClick(View v) {
//        mainMsg.setBackgroundResource(R.drawable.shape_circle_rect_msg_focus_left);
//        mainMsg.setTextColor(getResources().getColor(R.color.link_blue));
//        mainContact.setBackgroundResource(R.drawable.shape_circle_rect_msg_unfocus_right);
//        mainContact.setTextColor(getResources().getColor(R.color.text_color_white));
//        if (msgFragment == null) {
//            msgFragment = MsgFragment.newInstance();
//        }
//        switchFragment(currFragment, msgFragment);
    }

    @Event(R.id.mainContact)
    private void contactOnClick(View v) {
        mainMsg.setBackgroundResource(R.drawable.shape_circle_rect_msg_unfocus_left);
        mainMsg.setTextColor(getResources().getColor(R.color.text_color_white));
        mainContact.setBackgroundResource(R.drawable.shape_circle_rect_msg_focus_right);
        mainContact.setTextColor(getResources().getColor(R.color.link_blue));
        if (contactFragment == null) {
            contactFragment = ContactFragment.newInstance();
        }
        switchFragment(currFragment, contactFragment);
    }

    public void switchFragment(Fragment from, Fragment to) {
        if (from.equals(to)) return;
        if (to == null) return;
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (!to.isAdded()) {
            transaction.hide(from).add(R.id.msg_fragment_place_holder, to).commit();
        } else {
            transaction.hide(from).show(to).commit();
        }
        currFragment = to;
    }
}
